package com.zygh.lz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.lz.dao.*;
import com.zygh.lz.entity.*;
import com.zygh.lz.service.XlevelserviceService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.util.JwtTokenUtil;
import com.zygh.lz.util.JwtUtils;
import com.zygh.lz.util.TreeUtil;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.ResultBeans;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class XlevelserviceServiceImpl implements XlevelserviceService {
    @Resource
    private XlevelserviceMapper xlevelserviceMapper;

    @Resource
    private SectionMapper sectionMapper;


    @Resource
    private SptypeMapper sptypeMapper;

    @Resource
    private SignMapper signMapper;

    @Resource
    private SignEquipageMapper signEquipageMapper;

    @Resource
    private TreeUtil treeUtil;

    @Resource
    private StaffMapper staffMapper;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public ResultBean delSpecialService(Integer id) {
        return ResultUtil.execOp(xlevelserviceMapper.deleteById(id), "删除");
    }


    @Override
    public ResultBean updateSpecialService(Xlevelservice xlevelservice) {
        return ResultUtil.execOp(xlevelserviceMapper.updateByPrimaryKeySelective(xlevelservice), "修改");
    }

    @Override
    public List<Xlevelservice> selectXlevelservice(Integer type) {
        return xlevelserviceMapper.selectXlevelservice(type);

    }


    @Override
    public ResultBeans findSpecialById(Integer sectionId, String policeNumber) {
        List<Map<String, Object>> stairDuty = xlevelserviceMapper.findStairDuty();
        //1.遍历岗位信息
        //2.查询pid和id相等的
        //3set id下面
        List<Map<String, Object>> maps = treeUtil.buildByRecursive(stairDuty, policeNumber);
        return ResultUtil.resultBeansSuccess(maps);
    }

    /**
     * =====================================特殊勤务右侧详情栏信息===============================================
     */

    @Override
    public List<Map> findSpecialStair(Integer sectionId) {
        List<Map> sptypes = sptypeMapper.selectSptypeAll(sectionId);
        for (Map sptype : sptypes) {
            //岗位数
            int count = xlevelserviceMapper.findStationNum(Integer.valueOf(sptype.get("lx").toString()), null);
            //部署警力
            int number = xlevelserviceMapper.finddePloyPtrength(Integer.valueOf(sptype.get("lx").toString()), null);
            sptype.put("count", count);
            sptype.put("number", number);
        }
        return sptypes;
    }


    @Override
    public ResultBean addSpecialServiceTree(Xlevelservice xlevelservice) {
        return ResultUtil.execOp(xlevelserviceMapper.insertSelective(xlevelservice), "新增");
    }

    @Override
    public ResultBean updateSpecialServiceTree(Xlevelservice xlevelservice) {
        return ResultUtil.execOp(xlevelserviceMapper.updateById(xlevelservice), "修改");
    }

    @Override
    public List<Map> findTree() {
        List<Map<String, Object>> stairDuty = sptypeMapper.selectMaps(Wrappers.<Sptype>lambdaQuery()
                .eq(Sptype::getYxzt, 1));
        return treeUtil.buildTree(stairDuty);
    }


    @Override
    public ResultBean findPeople(HttpServletRequest request, Integer positionId) {
        //分权限
        //查看登录人信息
        String token = request.getHeader("token");
        String userName = jwtTokenUtil.getUserNameFromToken(token);
        //处于哪个支队下面登录人
        Staff staff = staffMapper.selectOne(Wrappers.<Staff>lambdaQuery().eq(Staff::getStaffTel, userName));

        //根据支队查看特殊勤务
        List<Xlevelservice> list = xlevelserviceMapper.selectList(Wrappers.<Xlevelservice>lambdaQuery()
                .eq(Objects.nonNull(positionId), Xlevelservice::getPositionId, positionId));
        return ResultUtil.setOK("查询成功", list);
    }

    @Override
    public ResultBean policeDistribute() {
        //1 查出来各个岗位
        //2 各个岗位
        List<Map<String, Object>> stairDuty = sptypeMapper.selectMaps(Wrappers.<Sptype>lambdaQuery().eq(Sptype::getYxzt, 1));
        stairDuty.forEach(x -> {
            List<Xlevelservice> xlevelservices = xlevelserviceMapper.selectList(Wrappers.<Xlevelservice>lambdaQuery()
                    .eq(Xlevelservice::getPositionId, x.get("id")));
            x.put("people", 0);
            x.put("count", 0);

            if (CollUtil.isNotEmpty(xlevelservices)) {
                int sum = xlevelservices.stream().filter(y -> Objects.nonNull(y.getNumber())).mapToInt(Xlevelservice::getNumber).sum();
                x.put("people", sum);
                x.put("count", xlevelservices.size());
            }
        });

        List<Map> maps = treeUtil.buildTreePolice(stairDuty);
        return ResultUtil.setOK("查询成功", maps);
    }

    @Override
    public ResultBean policeDetail(Integer positionId) {
        List<Xlevelservice> xlevelservices = xlevelserviceMapper.selectList(Wrappers.<Xlevelservice>lambdaQuery().eq(Xlevelservice::getPositionId, positionId));
        return ResultUtil.setOK("查询成功", xlevelservices);
    }

    @Override
    public ResultBean policeNow(Integer positionId, Integer deptId) {
        List<Integer> pids = new ArrayList<>();
        List<Integer> existsPids = new ArrayList<>();

        List<Integer> sectionIds = new ArrayList<>();

        if (Objects.nonNull(deptId)) {
            List<Section> sections = sectionMapper.selectList(Wrappers.<Section>lambdaQuery().eq(Section::getSectionPid, deptId).or().eq(Section::getSysSectionId, deptId));
            sectionIds = sections.stream().map(Section::getSysSectionId).collect(Collectors.toList());
        }

        if (Objects.nonNull(positionId)) {
            pids.add(positionId);

            List<Integer> childIds;
            do {
                existsPids.addAll(pids);
                List<Sptype> child = sptypeMapper.selectList(Wrappers.<Sptype>lambdaQuery().in(Sptype::getPid, pids));
                childIds = child.stream().map(Sptype::getId).collect(Collectors.toList());
                pids = childIds;
            } while (CollUtil.isNotEmpty(childIds));
        }
        List<Xlevelservice> xlevelservices = xlevelserviceMapper.selectList(Wrappers.<Xlevelservice>lambdaQuery().in(CollUtil.isNotEmpty(existsPids), Xlevelservice::getPositionId, existsPids));

        List<Integer> collect = xlevelservices.stream().map(Xlevelservice::getId).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            return ResultUtil.setOK("查询成功", null);
        }
        //查询当天签到信息
        List<Sign> signs = signMapper.selectList(Wrappers.<Sign>lambdaQuery()
                .in(Sign::getAssignmentid, collect)
                .eq(Sign::getComment, 2)
                .likeRight(Sign::getSignintime, DateUtil.today()));
        List<Integer> staffIds = signs.stream().map(Sign::getStaffid).collect(Collectors.toList());

        Map<String, Object> data = new HashMap<>(4);
        if (CollUtil.isNotEmpty(staffIds)) {
            Integer otherNumOnline = staffMapper.selectCount(Wrappers.<Staff>lambdaQuery()
                    .in(Staff::getSysStaffId, staffIds)
                    .in(CollUtil.isNotEmpty(sectionIds), Staff::getSysSectionId, sectionIds)
            );

            data.put("otherNumOnline", otherNumOnline);

        } else {
            data.put("otherNumOnline", 0);

        }
        //查询当班在线警力
        List<Sign> signsOnline = signMapper.selectList(Wrappers.<Sign>lambdaQuery()
                .in(Sign::getAssignmentid, collect)
                .eq(Sign::getComment, 2)
                .eq(Sign::getState, 1));
        List<Integer> staffIdsOnline = signsOnline.stream().map(Sign::getStaffid).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(signsOnline)) {
            Integer otherNum = staffMapper.selectCount(Wrappers.<Staff>lambdaQuery()
                    .in(Staff::getSysStaffId, staffIdsOnline)
                    .in(CollUtil.isNotEmpty(sectionIds), Staff::getSysSectionId, sectionIds)
            );

            data.put("otherNum", otherNum);
        } else {

            data.put("otherNum", 0);
        }
        //签到岗位(签到数)
        List<Integer> collect1 = signsOnline.stream().map(Sign::getAssignmentid).collect(Collectors.toList());
        data.put("postNum", 0);
        if (CollUtil.isNotEmpty(collect1)) {
            Integer integer = xlevelserviceMapper.selectCount(Wrappers.<Xlevelservice>lambdaQuery().in(Xlevelservice::getId, collect1));
            data.put("postNum", integer);
        }
        List<String> signNumList = signs.stream().map(Sign::getSignnum).collect(Collectors.toList());
        Integer equipageNumber = 0;
        if (signNumList.size() > 0) {
            equipageNumber = signEquipageMapper.selectCount(Wrappers.<SignEquipage>lambdaQuery().in(SignEquipage::getSignnum, signNumList));
        }

        data.put("equipageNumber", equipageNumber);
        //查询时间段
        DateTime date = DateUtil.date();
        DateTime dateTime = DateUtil.offsetHour(DateUtil.beginOfDay(DateUtil.date()), 8);
        DateTime dateTime1 = DateUtil.offsetHour(DateUtil.beginOfDay(DateUtil.date()), 20);
        //任务起数 二级分类的数量
        Integer taskCount = sptypeMapper.selectCount(Wrappers.<Sptype>lambdaQuery().eq(Sptype::getPid, 0));
        data.put("taskCount", taskCount);
        boolean between = DateUtil.isIn(date, dateTime, dateTime1);
        if (between) {
            data.put("time", "08:30-20:00");
        } else {
            data.put("time", "20:00-次日08:30");
        }
        return ResultUtil.setOK("查询成功", data);
    }

    @Override
    public List<Map> findtree() {
        List<Map<String, Object>> stairDuty = sptypeMapper.selectMaps(Wrappers.<Sptype>emptyWrapper());
        return treeUtil.buildTree(stairDuty);
    }

    @Override
    public ResultBean insertAll(List<Xlevelservice> result) {
        for (Xlevelservice xlevelservice : result) {
            //执勤单位
            String sectionName = xlevelservice.getSectionId();
            //所属岗位
            String position = xlevelservice.getPosition();

            Section section = sectionMapper.selectOne(Wrappers.<Section>lambdaQuery()
                    .eq(Section::getSectionName, sectionName));
            Sptype sptype = sptypeMapper.selectOne(Wrappers.<Sptype>lambdaQuery()
                    .eq(Sptype::getSsname, position));

            xlevelservice.setSectionId(String.valueOf(section.getSysSectionId()));
            xlevelservice.setPositionId(sptype.getId());
            xlevelservice.setZt(1);
            xlevelservice.setRwid("31157de61e6afff0b45bf9b3f3df38f1");

            xlevelserviceMapper.insert(xlevelservice);
        }
        return ResultUtil.execOp(1, "插入");
    }


}